package bancosys.tec.rtm.impl.diagnostician;

import java.io.Serializable;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;

import bancosys.tec.rtm.diagnostician.AbstractDiagnostician;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;

/**
 * Diagnostician que mostra os beans da beanfactory
 * 
 * @author takeshi
 */
public class BeanNamesAndClassDiagnostician extends AbstractDiagnostician implements BeanFactoryAware, Serializable {

    private transient BeanFactory bf;

    /**
     * Construtor.
     */
    public BeanNamesAndClassDiagnostician() {
        // nothing
    }

    /**
     * Construtor.
     * 
     * @param bf bean factory.
     */
    public BeanNamesAndClassDiagnostician(BeanFactory bf) {
        this.bf = bf;
    }

    /**
     * {@inheritDoc}
     */
    public String getName() {
        return "BeanFactory bean definitions";
    }

    /**
     * {@inheritDoc}
     * 
     * @see bancosys.tec.rtm.diagnostician.Diagnostician#diagnosis()
     */
    @Override
    protected boolean fillDiagnosisBean(DiagnosisBean bean) throws Exception {
        if (bf instanceof ListableBeanFactory) {
            ListableBeanFactory lbf = (ListableBeanFactory) bf;
            String[] beanDefinitionNames = lbf.getBeanDefinitionNames();
            for (String string : beanDefinitionNames) {
                try {
					Object obj = bf.getBean(string);
					bean.addDescription(string + " => " + obj);
				} catch (Exception e) {
					bean.addDescription(string + " => " + e.getMessage());
				}
            }
            return true;
        } else {
            bean.addDescription("BeanFactory nao implementa ListableBeanFactory");
            return false;
        }
    }

    /**
     * {@inheritDoc}
     */
    public void setBeanFactory(BeanFactory beanFactory) {
        this.bf = beanFactory;
    }
}
